<?php
/**
 * Created by PhpStorm.
 * User: lhl
 * Date: 2020/11/27
 * Time: 12:14
 * Features: 后台用户
 */

namespace app\adminapiv3\model;



use app\adminapiv3\service\Password;

class ServerUserModel extends BaseModel
{
    /**
     * 管理员重置登录密码
    */
    public function resetPassword($param){
        //验证当前登录用户的密码
        $loginUserId = $this->getLoginUserId();
        $loginUserInfo = $this->getInfoById($loginUserId,'id,password,salt');
        if(!$loginUserInfo){
            $this->forcedLogout();
        }
        $serverPassword = new Password();
        if (!$serverPassword->decrypt($param['login_user_password'], $loginUserInfo['salt'], $loginUserInfo['password'])) {
            $this->setError($this->CODE_FAIL, '当前登录用户密码不正确');
            return false;
        }

        //修改该用户密码
        $userInfo = $this->getInfoById($param['id'],'id,password,salt');
        if(!$userInfo){
            $this->setError($this->CODE_FAIL, '用户数据不存在');
            return false;
        }

        $param['salt'] = createSalt(6);
        $param['password'] = $serverPassword->encrypt($param['password'], $param['salt']);
        $this->allowField(true)->update($param,['id' => $param['id']]);
        return true;
    }

    /**
     * 根据id查询用户信息
    */
    public function getInfoById($id,$field = '*'){
        return $this->where('id',$id)->field($field)->findOrEmpty()->toArray();
    }

    /**
     * 根据资产组id,查询用户信息
     * @param string $hostGroupId 资产组id,逗号隔开字符串
    */
    public function getUsersByHostGroupId($hostGroupId,$field = '*'){
        return $this->whereIn('host_group_id',$hostGroupId)->field($field)->select()->toArray();
    }

}